<?php
/**
 *
 * PostFunction.php
 *
 * 发帖常用方法集
 *
 * @author     limin<lmin@vip.deyi.com>
 * @since      2015/7/13 10:36
 * @copyright  deyi.com
 *　
 */

namespace Deyi\Functions;

class PostFunction
{
    /**
     * 格式化帖子内容, 包括过滤、替换、转换等，但不包括敏感词处理
     * @param $msg
     * @return mixed
     */
    public static function formatMesseage($msg)
    {
        $msg = str_ireplace('<br>', PHP_EOL, $msg);
        $msg = str_ireplace('<br />', PHP_EOL, $msg);
        $msg = preg_replace('/<|>/U', '', $msg);
        $msg = static::convertUbbURL($msg);

        return $msg;
    }

    /**
     * 转换成UBB的URL标签
     * @param $str
     * @return mixed
     */
    public static function convertUbbURL($str)
    {
        $pattern = '/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]*?/i';
        preg_match_all($pattern, ' ' . $str, $p_res);

        $p_str = ((isset($p_res[0])) && (!empty($p_res[0]))) ? $p_res[0] : [];
        foreach ($p_str as $v) {
            $str = str_ireplace($v, "[url]" . $v . "[/url]", $str);
        }

        return self::cleanWrongUrlTag($str);
    }

    /**
     * 修复因转义导致的url标签bug(针对音频帖子)
     *
     * @author liang<lang@vip.deyi.com>
     * @param $str
     * @return mixed
     */
    public static function cleanWrongUrlTag($str)
    {
        return preg_replace('/\[url=\[url\](.*?)\[\/url\]\]/', '[url=$1]', $str);
    }
}
